<?php
declare(strict_types=1);

namespace Swb\Shop\Service;


use Hyperf\Database\Model\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\ApplicationContext;
use Swb\Shop\Contract\ShopServiceInterface;
use Swb\Shop\Helper\ShopTrait;
use Swb\Shop\Model\TProject;

class ProjectService implements ShopServiceInterface
{
	use ShopTrait;
	public function getList(array $param=[])
	{
		$request        =ApplicationContext::getContainer()->get(RequestInterface::class);
		$keyword        =$search_param['keyword']??$request->input('keyword');
		$page           =$search_param['page']??$request->input('page', 1);
		$limit          =$search_param['limit']??$request->input('limit', 20);
		$area           =$search_param['area']??$request->input('area');
		$price          =$search_param['price']??$request->input('price', 0);
		$total_price    =$search_param['total_price']??$request->input('total_price', 0);
		$agent_id       =$search_param['agent_id']??$request->input('agent_id', 0);
		$type           =$search_param['type']??$request->input('type', 2);
		$business_id    =$search_param['business_id']??$request->input('business_id', 0);
		$build_id   =   $search_param['build_id']??$request->input('build_id', 0);
		$except_hours_id=$search_param['except_hours_id']??$request->input('except_hours_id', 0);
		$count          =TProject::query()->whereHas('house', function ($builder) use ($type){
			if ($type==2){
				$builder->where('house_sale_rent', 1)->where('del_flag', 1);
			}
			if ($type==3){
				$builder->where('house_sale_rent', 2)->where('del_flag', 1);
			}

		})->where('del_flag', 1)
			->where('up_down_status', 1)
			->whereIn('project_status', [1, 2])->when($keyword, function (Builder $builder, $keyword){
			$builder->whereHas('building', function (Builder $query) use ($keyword){
				$query->where('t_building.building_address', 'like', "%$keyword%")->orWhere('t_building.building_name', 'like', "%$keyword%");
			});
		})->when($build_id,function ($builder,$build_id){
				$builder->where('building_id',$build_id);
			})
			->when($agent_id, function ($builder, $agent_id){
			$builder->where('manager_id', $agent_id);
		})->when($area, function ($builder, $area){
			$builder->whereHas('building', function (Builder $query) use ($area){
				$isArea=Db::table('sys_business_areas')->where('id', $area)->count();
				if ($isArea){
					$query->where('business_district_id', $area);
				}else{
					$area=Db::table('sys_business_areas')->where('area_id', $area)->pluck('id');
					$query->whereIn('business_district_id', $area);
				}
			});
		})->where(function ($builder) use ($price, $type){
			if ($price){
				$price=explode('-', $price);
				if (is_array($price)){
					$min_price  =$price[0];
					$max_price  =!isset($price[1]) ? 1000000000000 : $price[1];
					$project_ids=Db::table('t_shop')->whereExists(function ($query) use ($min_price, $max_price, $type){
						if ($type==2){
							$query->where('house_source', 2)->where('house_sale_rent', 1)->whereRaw('(rental_price*floor_area) between ? and ?', [$min_price, $max_price]);
						}
						if ($type==3){
							$query->where('house_source', 2)->where('house_sale_rent', 2)->whereRaw('(sale_price*floor_area) between ? and ?', [$min_price, $max_price]);
						}
					})->distinct()->pluck('project_id');
					if ($project_ids){
						return $builder->whereIn('id', $project_ids);
					}
				}

			}
		})->when($total_price, function (Builder $builder, $total_price){
			$price=explode('-', $total_price);
			if (is_array($price)){
				$min_price  =$price[0];
				$max_price  =!isset($price[1]) ? 1000000000000 : $price[1];
				$project_ids=Db::table('t_shop')->whereExists(function ($query) use ($min_price, $max_price){

					$query->where('house_source', 2)->where('house_sale_rent', 2)->whereRaw('(sale_price*floor_area) between ? and ?', [$min_price, $max_price]);

				})->distinct()->pluck('project_id');
				if ($project_ids){
					return $builder->whereIn('id', $project_ids);
				}
			}
		})->when($business_id, function ($builder, $business_id){
			return $builder->whereIn('id', $business_id);
		})->where(function ($builder) use ($request){
			$floorarea=$request->input('floorarea', 0);
			if ($floorarea){
				$floorarea=explode('-', $floorarea);
				if (is_array($floorarea)){
					$min_floor_area=$floorarea[0];
					$max_floor_area=$floorarea[1]??1000000000000;
					$project_ids   =Db::table('t_shop')->whereExists(function ($query) use ($min_floor_area, $max_floor_area){
						$query->where('house_source', 2)->where('house_sale_rent', 2)->whereBetween('floor_area', [$min_floor_area, $max_floor_area]);
					})->distinct()->pluck('project_id');
					if ($project_ids){
						return $builder->whereIn('id', $project_ids);
					}
				}
			}
		})->where(function (Builder $builder) use ($request){
			$renovation_type=$request->input('renovation_type');
			if ($renovation_type){
				$label=explode(',', $renovation_type);
				return $builder->whereHas('building', function (Builder $query) use ($label){
					$query->whereIn('decorate_status', $label);
				});
			}


		})->where(function (Builder $builder) use ($request){
			$infrastructure=$request->input('infrastructure');
			if ($infrastructure){
				$label=explode(',', $infrastructure);
				return $builder->whereHas('house_dict', function ($query) use ($label){
					$query->whereIn('tag_id', $label);
				});
			}
		})->where(function ($builder) use ($request){
			$label=$request->input('label');
			if ($label){
				//标签
				$label=explode(',', $label);
				return $builder->whereHas('building', function ($query) use ($label){
					$query->leftJoin('t_building_dictionaries', 't_building_dictionaries.building_id', '=', 't_building.id')->where('t_building_dictionaries.building_info_type', 1)->whereIn('dict_id', $label);
				});
			}
		})->where(function ($builder) use ($request){
			$industries=$request->input('industries');
			if ($industries){
				//适合业态
				$label=explode(',', $industries);
				return $builder->whereHas('house', function ($query) use ($label){
					$query->leftJoin('t_house_dictionaries', 't_house_dictionaries.house_id', '=', 't_shop.id')->where('t_house_dictionaries.type', 2)->whereIn('dictionaries_id', $label);
				});

			}
		})->where(function ($builder) use ($request){
			$rent_free_period=$request->input('rent_free_period');
			if ($rent_free_period){
				//免租期
				return $builder->whereHas('house', function ($query){
					$query->where('rent_free_period', 200);
				});

			}
		})->where(function ($builder) use ($request){
			$contract_term=$request->input('contract_term');
			if ($contract_term){
				//合同期 数字
				return $builder->whereHas('house', function ($query) use ($contract_term){
					$query->where('contract_term', $contract_term);
				});
				//
			}
		})->when($except_hours_id, function (Builder $builder, $except_hours_id){
			$builder->where('id', '<>', $except_hours_id);
		})->count();
		if ($count){
			$list=TProject::query()->with(['building', 'building_dict'=>function ($query){
					$query->where('building_info_type', 1)->select('dict_name', 'building_id');
				}])->when($agent_id, function ($builder, $agent_id){
					$builder->where('manager_id', $agent_id);
				})->where('del_flag', 1)->where('up_down_status', 1)->whereIn('project_status', [1, 2])->when($keyword, function (Builder $builder, $keyword){
					$builder->whereHas('building', function (Builder $query) use ($keyword){
						$query->where('t_building.building_address', 'like', "%$keyword%")->orWhere('t_building.building_name', 'like', "%$keyword%");
					});
				})->whereHas('house', function ($builder) use ($type){
					if ($type==2){
						$builder->where('house_sale_rent', 1)->where('del_flag', 1);
					}
					if ($type==3){
						$builder->where('house_sale_rent', 2)->where('del_flag', 1);
					}

				})->when($area, function ($builder, $area){
					$builder->whereHas('building', function (Builder $query) use ($area){
						$isArea=Db::table('sys_business_areas')->where('id', $area)->count();
						if ($isArea){
							$query->where('business_district_id', $area);
						}else{
							$area=Db::table('sys_business_areas')->where('area_id', $area)->pluck('id');
							$query->whereIn('business_district_id', $area);
						}
					});
				})->where(function ($builder) use ($price, $type){
					if ($price){
						$price=explode('-', $price);
						if (is_array($price)){
							$min_price  =$price[0];
							$max_price  =!isset($price[1]) ? 1000000000000 : $price[1];
							$project_ids=Db::table('t_shop')->whereExists(function ($query) use ($min_price, $max_price, $type){
								if ($type==2){
									$query->where('house_source', 2)->where('house_sale_rent', 1)->whereRaw('(rental_price*floor_area) between ? and ?', [$min_price, $max_price]);
								}
								if ($type==3){
									$query->where('house_source', 2)->where('house_sale_rent', 2)->whereRaw('(sale_price*floor_area) between ? and ?', [$min_price, $max_price]);
								}
							})->distinct()->pluck('project_id');
							if ($project_ids){
								return $builder->whereIn('id', $project_ids);
							}
						}

					}
				})->when($total_price, function (Builder $builder, $total_price){
					$price=explode('-', $total_price);
					if (is_array($price)){
						$min_price  =$price[0];
						$max_price  =!isset($price[1]) ? 1000000000000 : $price[1];
						$project_ids=Db::table('t_shop')->whereExists(function ($query) use ($min_price, $max_price){
							$query->where('house_source', 2)->where('house_sale_rent', 2)->whereRaw('(sale_price*floor_area) between ? and ?', [$min_price, $max_price]);
						})->distinct()->pluck('project_id');
						if ($project_ids){
							return $builder->whereIn('id', $project_ids);
						}
					}
				})->where(function ($builder) use ($request){
					$floorarea=$request->input('floorarea', 0);
					if ($floorarea){
						$floorarea=explode('-', $floorarea);
						if (is_array($floorarea)){
							$min_floor_area=$floorarea[0];
							$max_floor_area=$floorarea[1]??1000000000000;
							$project_ids   =Db::table('t_shop')->whereExists(function ($query) use ($min_floor_area, $max_floor_area){
								$query->where('house_source', 2)->where('house_sale_rent', 2)->whereBetween('floor_area', [$min_floor_area, $max_floor_area]);
							})->distinct()->pluck('project_id');
							if ($project_ids){
								return $builder->whereIn('id', $project_ids);
							}
						}
					}
				})->where(function (Builder $builder) use ($request){
					$renovation_type=$request->input('renovation_type');
					if ($renovation_type){
						$label=explode(',', $renovation_type);
						return $builder->whereHas('building', function (Builder $query) use ($label){
							$query->whereIn('decorate_status', $label);
						});
					}
				})->when($business_id, function ($builder, $business_id){
					return $builder->whereIn('id', $business_id);
				})->where(function (Builder $builder) use ($request){
					$infrastructure=$request->input('infrastructure');
					if ($infrastructure){
						$label=explode(',', $infrastructure);
						return $builder->whereHas('house_dict', function ($query) use ($label){
							$query->whereIn('tag_id', $label);
						});
					}
				})->where(function ($builder) use ($request){
					$label=$request->input('label');
					if ($label){
						//标签
						$label=explode(',', $label);
						return $builder->whereHas('building', function ($query) use ($label){
							$query->leftJoin('t_building_dictionaries', 't_building_dictionaries.building_id', '=', 't_building.id')->where('t_building_dictionaries.building_info_type', 1)->whereIn('dict_id', $label);
						});
					}
				})->where(function ($builder) use ($request){
					$industries=$request->input('industries');
					if ($industries){
						//适合业态
						$label=explode(',', $industries);
						return $builder->whereHas('house', function ($query) use ($label){
							$query->leftJoin('t_house_dictionaries', 't_house_dictionaries.house_id', '=', 't_shop.id')->where('t_house_dictionaries.type', 2)->whereIn('dictionaries_id', $label);
						});

					}
				})
				->when($build_id,function ($builder,$build_id){
					$builder->where('building_id',$build_id);
				})
				->where(function ($builder) use ($request){
					$rent_free_period=$request->input('rent_free_period');
					if ($rent_free_period){
						//装修类型
						return $builder->whereHas('house', function ($query){
							$query->where('rent_free_period', 200);
						});
					}
				})->where(function ($builder) use ($request){
					$contract_term=$request->input('contract_term');
					if ($contract_term){
						//合同期 数字
						return $builder->whereHas('house', function ($query) use ($contract_term){
							$query->where('contract_term', $contract_term);
						});
					}
				})->when($except_hours_id, function (Builder $builder, $except_hours_id){
					$builder->where('id', '<>', $except_hours_id);
				})->select('id', 'building_id')->orderByRaw('project_status asc,updated_at desc')->forPage($page, $limit)->get()->toArray();
			$collect_key=[];
			if ($business_id){
				$collect_key=array_flip((array)$business_id);
			}
			foreach ($list as &$item){
				$price = $this->get_project_price($item['id'],$type);
				$item['label']        =$item['building_dict']?array_column($item['building_dict'],'dict_name'):[];
				$item['district_name']=$item['building']['area_name'];
				$item['street_name']  =$item['building']['name'];
				$logo                 =$this->get_logo($item['id']);
				$item['name']         =$item['building']['building_name'];
				$item['avg_price']    =$type==2?$price['avg_price']:number_format($price['avg_price']/10000,2,'.','');
				$item['avg_total']    =$type==2?$price['avg_total']:number_format($price['avg_total']/10000,2,'.','');
				$price['avg_total2']  = $price['avg_total'];
				$item['min_area']     =$price['min_area'];
				$item['max_area']     =$price['max_area'];
				$item['logo']         =$logo ?: config('swb_shop.default_url');
				if ($collect_key){
					$item['business_id']=$item['id'];
					$item['collect_id'] =$collect_key[$item['id']];
				}
			}
		}
		$response['lists']=$list??[];
		$response['limit']=(int)$limit;
		$response['page'] =(int)$page;
		$response['count']=$count;
		return $response;
	}

	public function getDetail(string $id)
	{
		try{
			$request = ApplicationContext::getContainer()->get(RequestInterface::class);
			return  $this->get_sell_new_shop($id,$request->input('type'));
		}catch (\Throwable $e)
		{
			return false;
		}

	}
}